import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}


Vue.use(VueRouter)

const routes = [{
    name: 'login',
    path: '/login',
    component: () =>
        import ('@/views/login')
}, {
    // name: 'layout',
    path: '/',
    component: () =>
        import ('@/views/layout'),
    children: [{
        name: 'home',
        path: '/',
        component: () =>
            import ('@/views/home'),
    }, {
        name: 'user',
        path: '/user',
        component: () =>
            import ('@/views/user'),
    }, {
        name: 'qa',
        path: '/qa',
        component: () =>
            import ('@/views/qa'),
    }, {
        name: 'video',
        path: '/video',
        component: () =>
            import ('@/views/video'),
    }, ]
}, {
    name: 'shoucang',
    path: '/shoucang',
    component: () =>
        import ('@/views/user/shoucang'),
    meta: {
        needLogin: true
    }
}, {
    name: 'lishi',
    path: '/lishi',
    component: () =>
        import ('@/views/user/lishi'),
    meta: {
        needLogin: true
    }
}, {
    name: 'profile',
    path: '/user/profile',
    component: () =>
        import ('@/views/user/profile'),
    meta: {
        needLogin: true
    }

}, {
    name: 'search',
    path: '/search',
    component: () =>
        import ('@/views/search'),

}, {
    name: 'article',
    path: '/article/:articleId',
    component: () =>
        import ('@/views/article'),
    props: true

}]

const router = new VueRouter({
    routes
})

// 设置导航守卫
router.beforeEach((to, from, next) => {
    if (to.meta.needLogin) {
        if (store.state.user) {
            next()
        } else {
            next('/login?redirect=' + to.path)
        }
    } else {
        next()
    }
})

export default router